package com.example.bookshop.service.impl;

import com.example.bookshop.VO.CartItemVO;
import com.example.bookshop.entity.Book;
import com.example.bookshop.entity.Cart;
import com.example.bookshop.entity.User;
import com.example.bookshop.mapper.BookMapper;
import com.example.bookshop.mapper.CartMapper;
import com.example.bookshop.mapper.UserMapper;
import com.example.bookshop.service.CartService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @auth shanyue
 * @date 2025年06月05日15:15
 */
@Service
public class CartServiceImpl implements CartService {

    @Resource
    private BookMapper bookMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private CartMapper cartMapper;

    @Override
    public List<CartItemVO> getCartItems(String username) {
        Integer userId = cartMapper.findUserIdByUsername(username);
        if (userId == null) {
            return new ArrayList<>();
        }

        List<Cart> cartList = cartMapper.findByUserId(userId);
        List<CartItemVO> cartItems = new ArrayList<>();
        BigDecimal totalPrice = BigDecimal.ZERO;

        if (cartList != null) {
            for (Cart cart : cartList) {
                if (cart.getBookId() == null) {
                    continue;
                }
                Book book = bookMapper.findById(cart.getBookId());
                if (book == null) {
                    continue;
                }
                CartItemVO item = new CartItemVO();
                item.setCart(cart);
                item.setBook(book);

                // 计算小计
                if (book.getPrice() != null) {
                    BigDecimal subTotal = book.getPrice().multiply(BigDecimal.valueOf(cart.getQuantity()));
                    item.setSubTotal(subTotal);
                    totalPrice = totalPrice.add(subTotal);
                } else {
                    item.setSubTotal(BigDecimal.ZERO);
                }

                cartItems.add(item);
            }
        }

        return cartItems;
    }

    @Override
    public BigDecimal getTotalPrice(String username) {
        Integer userId = cartMapper.findUserIdByUsername(username);
        if (userId == null) {
            return BigDecimal.ZERO;
        }

        List<Cart> cartList = cartMapper.findByUserId(userId);
        BigDecimal totalPrice = BigDecimal.ZERO;

        if (cartList != null) {
            for (Cart cart : cartList) {
                if (cart.getBookId() == null) {
                    continue;
                }
                Book book = bookMapper.findById(cart.getBookId());
                if (book != null && book.getPrice() != null) {
                    BigDecimal subTotal = book.getPrice().multiply(BigDecimal.valueOf(cart.getQuantity()));
                    totalPrice = totalPrice.add(subTotal);
                }
            }
        }

        return totalPrice;
    }

    @Override
    @Transactional
    public String addToCart(int bookId, int quantity, String username) {
        User user = userMapper.findByUsername(username);
        Book book = bookMapper.findById(bookId);

        if (quantity <= 0) {
            return "购买数量必须大于0";
        }

        if (book == null) {
            return "图书不存在";
        }

        if (quantity > book.getStock()) {
            return "库存不足";
        }

        Cart existing = cartMapper.findByUserIdAndBookId(user.getId(), bookId);
        if (existing != null) {
            int newQuantity = existing.getQuantity() + quantity;
            if (newQuantity > book.getStock()) {
                return "库存不足，已存在的购物车数量加上购买数量超过库存";
            }
            existing.setQuantity(newQuantity);
            cartMapper.update(existing);
        } else {
            Cart cart = new Cart(null, user.getId(), bookId, quantity);
            cartMapper.insert(cart);
        }

        return "加入购物车成功";
    }

    @Override
    @Transactional
    public String removeFromCart(int cartId, String username) {
        Cart cart = cartMapper.findById(cartId);
        if (cart != null) {
            cartMapper.deleteById(cartId);
            return "已移除";
        } else {
            return "购物车项不存在";
        }
    }

}
